package com.eco.fanliapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eco.fanliapp.common.constant.NewsEnumLog;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.AppUserMapper;
import com.eco.fanliapp.dao.AppUserRedRewardMapper;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.DateFormatUtils;
import com.eco.fanliapp.vo.AppUserRedRewardVo;
import com.eco.fanliapp.vo.RedRewardInvitationListVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 红包接口实现类
 */
@Service
public class AppUserRedRewardServiceImpl extends ServiceImpl<AppUserRedRewardMapper, AppUserRedReward> implements IAppUserRedRewardService {


    private static final Logger log = LoggerFactory.getLogger(AppUserRedRewardServiceImpl.class);

    @Autowired
    private AppUserRedRewardMapper appUserRedRewardMapper;

    @Autowired
    private IAppUserService iAppUserService;

    @Autowired
    private IAppNewsLogService iAppNewsLogService;

    @Autowired
    private UpdateUserCommon updateUserCommon;

    @Autowired
    private AppUserMapper appUserMapper;

    @Autowired
    private ISySwitchService sySwitchService;

    @Autowired
    private IAppUserRewardSetupService iAppUserRewardSetupService;

    @Autowired
    private ISySwitchService iSySwitchService;

    @Autowired
    private ISyUserMoneyService iSyUserMoneyService;
    @Autowired
    private ISyUserMoneyLogService syUserMoneyLogService;
    @Autowired
    private RedisTemplateService redisTemplateService;
    @Autowired
    private RedisLockService redisLockService;

    @Override
    public List<AppUserRedReward> selectStatus(String status, String type) {
        return appUserRedRewardMapper.selectStatus(status, type);
    }

    @Override
    public int selectCountByStatusType(int status, int type) {
        return appUserRedRewardMapper.selectCountByStatusType(status, type);
    }

    @Override
    public int add(AppUserRedReward appUserRedReward) {
        return appUserRedRewardMapper.insertSelective(appUserRedReward);
    }

    @Override
    public int updateAppUserRedReward(Long orderId, int status) {
        return appUserRedRewardMapper.updateAppUserRedReward(orderId, status);
    }

    @Override
    public List<AppUserRedReward> selectAppUserRedReward(Long stime, Long etime) {
        return appUserRedRewardMapper.selectAppUserRedReward(stime,etime);
    }

    @Override
    public ServerResponse<Map> getTotalMoney(Long userId) {
        HashMap<String, BigDecimal> totalMoney = appUserRedRewardMapper.getTotalMoney(userId);
        return ServerResponse.createBySuccess("查询成功", totalMoney);
    }

    @Override
    public Map invitationMakeMoneyCash(Long userId) {
        return appUserRedRewardMapper.selectHbMoney(userId);
    }

    @Override
//    @Transactional
    public ServerResponse updateHbStatus(AppUserRedReward appUserRedReward) {
        if (appUserRedReward.getTableId() == null) return ServerResponse.createByErrorMessage("参数有误");
        //查询此红包是否存在
        AppUserRedReward oneAppUserRedReward = appUserRedRewardMapper.selectByPrimaryKey(Long.valueOf(appUserRedReward.getTableId()));
        if (StringUtils.isEmpty(oneAppUserRedReward)) return ServerResponse.createByErrorMessage("此红包不存在");
        //更新红包状态
        appUserRedReward.setExpireTime(new Date().getTime());
        appUserRedReward.setUpdateTime(new Date().getTime());
        int i = appUserRedRewardMapper.updateHbStatus(appUserRedReward);
        if (i > 0) {
            //int ktx = iAppUserService.updateBalance(oneAppUserRedReward.getHbMoney(), oneAppUserRedReward.getUserId());
            // TODO: 红包结算金额修改
            int ktx = updateUserCommon.UpdateUserMoney(oneAppUserRedReward.getHbMoney(), oneAppUserRedReward.getUserId(), 5);//好友首次购物
            if (ktx <= 0) return ServerResponse.createByErrorMessage("更新余额失败");
            else {
                log.info("用户提取红包金额到用户余额成功用户id{}红包金额{}", oneAppUserRedReward.getUserId(), oneAppUserRedReward.getHbMoney());
                //增加一条消息记录
                iAppNewsLogService.newsType(oneAppUserRedReward.getUserId(), NewsEnumLog.NEWS_FIRST_FENS.getNewsType(), oneAppUserRedReward.getHbMoney(), oneAppUserRedReward.getHbMoney().toString());
                return ServerResponse.createBySuccessMessage("提取成功");
            }
        } else return ServerResponse.createByErrorMessage("红包修改状态失败原因：" + "未到提取日期");
    }

    @Override
    public int updateReceiveHbStatus(AppUserRedReward appUserRedReward) {
        return appUserRedRewardMapper.updateHbStatus(appUserRedReward);
    }

    /**
     * 首购红包到账加钱
     */
    @Override
    public void updateHbStatusTask() {
        //查询此红包是否存在(首购任务自动到账)
        Long starTime = DateFormatUtils.getStartTime();
        Long endTime = DateFormatUtils.getEndTime();
        Long time = new Date().getTime();
        List<AppUserRedReward> appUserRedRewardList = appUserRedRewardMapper.selectByTask(starTime,endTime);
        if (appUserRedRewardList != null) {
            for (AppUserRedReward appUserRedReward : appUserRedRewardList) {
                //1首次查询用户钱中是否存在数据
                SyUserMoney oldSyUserMoney = iSyUserMoneyService.selectByUserId(appUserRedReward.getUserId());
                //2获取账户变动前余额
                BigDecimal cashBalanceAmount = new BigDecimal(0);
                if (oldSyUserMoney != null) {
                    cashBalanceAmount = oldSyUserMoney.getCashBalanceAmount();
                }
                //3更新红包状态
                if (appUserRedReward.getHbType() == 3) {
                    int i = appUserRedRewardMapper.updateRedMoneyTask(appUserRedReward.getTableId(), time);
                    if (i > 0) {
                        int ktx = 0;
                        log.info("红包==用户增加金额------oldSyUserMoney", appUserRedReward.getUserId(), oldSyUserMoney);
                        if (oldSyUserMoney == null) {//添加
                            SyUserMoney syUserMoney = new SyUserMoney();
                            syUserMoney.setUserId(appUserRedReward.getUserId());
                            syUserMoney.setCashBalanceAmount(appUserRedReward.getHbMoney());
                            syUserMoney.setCashTotalAmount(appUserRedReward.getHbMoney());
                            syUserMoney.setEnable(1);
                            ktx = iSyUserMoneyService.insertSyUserMoney(syUserMoney);
                            log.info("红包==用户增加金额1------金额{}", appUserRedReward.getHbMoney());
                        } else {//修改
                            ktx = iSyUserMoneyService.updateUserCashBalanceAmount(appUserRedReward.getHbMoney(), appUserRedReward.getUserId());
                            log.info("红包==用户增加金额2------金额{}", appUserRedReward.getHbMoney());
                        }


                        if (ktx <= 0) {
                            log.info("用户提取红包金额到用户余额失败用户id{}红包金额{}", appUserRedReward.getUserId(), appUserRedReward.getHbMoney());
                        } else {
                            updateUserCommon.UpdateUserTaskStatus(appUserRedReward.getUserId(), 5);
                            log.info("用户提取红包金额到用户余额成功用户id{}红包金额{}", appUserRedReward.getUserId(), appUserRedReward.getHbMoney());
                        }
                        //账户金额发生变动，添加账户变更日志
                        String remark = "首购红包到账";
                        Integer logStatus = 0;//加钱
                        syUserMoneyLogService.addSyUserMoneyLog(appUserRedReward.getUserId(), cashBalanceAmount, appUserRedReward.getHbMoney(), remark, null, logStatus);
                    }
                }

            }
        }
        log.info("更新任务红包领取定时任务执行结果updateHbStatusTask--->5");
    }

    @Override
    public void updateHbStatusTaskToUser() {
        //查询此红包是否存在(首购任务自动到账)
        Long starTime = DateFormatUtils.getStartTime();
        Long endTime = DateFormatUtils.getEndTime();
        Long time = new Date().getTime();
        List<AppUserRedReward> appUserRedRewardList = appUserRedRewardMapper.selectByTask(starTime,endTime);
        if (appUserRedRewardList != null) {
            for (AppUserRedReward appUserRedReward : appUserRedRewardList) {
                //1查询用户数据
                AppUser appUser = iAppUserService.selectAppUserByUserId(appUserRedReward.getUserId(),0);
                //2获取账户变动前余额
                BigDecimal cashBalance = appUser.getBalance();
                //3更新红包状态
                if (appUserRedReward.getHbType() == 3) {
                    int i = appUserRedRewardMapper.updateRedMoneyTask(appUserRedReward.getTableId(), time);
                    if (i > 0) {
                        int ktx = 0;
                       //首单红包加钱到支付宝余额
                        ktx = iAppUserService.updateAppUseraddbalance(appUser.getUserId(),appUserRedReward.getHbMoney());

                        if (ktx <= 0) {
                            log.info("用户提取红包金额到用户余额失败用户id{}红包金额{}", appUserRedReward.getUserId(), appUserRedReward.getHbMoney());
                        } else {
                            updateUserCommon.UpdateUserTaskStatus(appUserRedReward.getUserId(), 5);
                            log.info("用户提取红包金额到用户余额成功用户id{}红包金额{}", appUserRedReward.getUserId(), appUserRedReward.getHbMoney());
                        }
                        //账户金额发生变动，添加账户变更日志
                        String remark = "首购红包到账支付宝余额";
                        Integer logStatus = 0;//加钱
                        syUserMoneyLogService.addSyUserMoneyLog(appUserRedReward.getUserId(), cashBalance, appUserRedReward.getHbMoney(), remark, null, logStatus);
                    }
                }

            }
        }
        log.info("更新任务红包领取定时任务执行结果updateHbStatusTask--->5");
    }

    /**
     * 修改红包状态
     *
     * @param appUserRedReward
     * @return
     */
    @Override
    public int updateAppUserRedRewardExpireTime(AppUserRedReward appUserRedReward) {
        return appUserRedRewardMapper.updateAppUserRedRewardExpireTime(appUserRedReward);
    }

    /**
     * 查询获取任务红包
     *
     * @param userId
     * @return
     */

    @Override
    public Integer selectCountMoneyStatus(Long userId, int status) {
        return appUserRedRewardMapper.selectCountMoneyStatus(userId, status);
    }

    @Override
    public AppUserRedReward selectAppUserRedRewardById(Long orderId, Long userId) {
        return appUserRedRewardMapper.selectAppUserRedRewardById(orderId, userId);
    }

    /**
     * 未登录红包弹窗
     *
     * @return
     */
    @Override
    public ServerResponse getNotLoginRedMoney() {
        String redisKeyStr = "app_redpackage_login";
        Boolean onOff = false;//默认没有关闭叉号
        Boolean popUp = true;//true 有弹窗  false 没有弹窗
        HashMap map = new HashMap();
        if (redisTemplateService.hasKey(redisKeyStr)) {
            map = redisTemplateService.getTByKey(redisKeyStr, HashMap.class);
        }
        if(map.size() == 0 ){
            SySwitch redPopUp = iSySwitchService.getById(2);//id2是未登录红包弹窗开关
            SySwitch redOnOff = iSySwitchService.getById(3);//id3是未登录红包弹窗叉号开关
            if (redPopUp != null) {
                if (redPopUp.getState() == 1) {
                    //有弹窗
                    popUp = true;
                } else {
                    //没有
                    popUp = false;
                }

            }

            if (redOnOff != null) {
                if (redOnOff.getState() == 1) {
                    //有叉号
                    onOff = true;
                } else {
                    //没有
                    onOff = false;
                }

            }
            map.put("sumMoney", "8.36");
            map.put("onOff", onOff);
            map.put("popUp", popUp);
            redisTemplateService.set(redisKeyStr, map, 60 * 5);


        }
        if(map.size() > 0){
            return ServerResponse.createBySuccess("未登录红包弹窗", map);
        }else {
            return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
        }

    }

    /**
     * 邀请赚钱到账加钱
     *
     * @param appUser
     * @param appOrderDetail
     */
    @Override
    public void addInvitationedMoney(AppUser appUser, AppOrderDetail appOrderDetail) {
        //邀请赚钱到账加钱获取锁  (redis锁-时间 (10秒))
        long startTimes = System.currentTimeMillis() + 1000 * 10;
        if (!redisLockService.lock( "user_order_invitationed_task_lock_" + appUser.getUserId(), startTimes + "")) {
            log.info("用户userid{}邀请赚钱到账",appUser.getUserId());
            return ;
        }
        //判断是否有上级（没有上级不往下进行）
        if (!StringUtils.isEmpty(appUser.getSuperInviteCode())) {
            AppUser SJUser = iAppUserService.selectSuperUserInfoBySuperInviteCode(appUser.getSuperInviteCode());
            if (!StringUtils.isEmpty(SJUser)) {
                log.info("得到用户的上级id{}", SJUser.getUserId());
                //查询上级的红包状态（已经领取：不往下进行）
                QueryWrapper<AppUserRedReward> queryWrapper = new QueryWrapper<AppUserRedReward>();
                queryWrapper.eq("user_id", SJUser.getUserId()).eq("hb_type", 2).eq("from_user_id", appUser.getUserId());
                List<AppUserRedReward> appUserRedRewards = list(queryWrapper);
                boolean isNeddAdd = true;
                if (appUserRedRewards != null && appUserRedRewards.size() > 0) {
                    for (AppUserRedReward appUserRedReward : appUserRedRewards) {
                        if (appUserRedReward.getHbStatus() != null && appUserRedReward.getHbStatus() != 4) {
                            isNeddAdd = false;
                            break;
                        }
                    }
                }
                if (appUserRedRewards == null || isNeddAdd) {
                    log.info("未得到用户的上级红包{}", SJUser.getUserId());
                    //获取是否免单状态
                    Long goodFrees = appOrderDetail.getGoodFrees();
                    int free = 0;
                    if (goodFrees != null) {
                        free = goodFrees.intValue();
                    }
                    log.info("获取订单是否为免单的状态{}", free);
                    //获取红包相关的参数
                    AppUserRewardSetup appUserRewardSetup = iAppUserRewardSetupService.getAppUserRewardSetup(1);
                    if (free == 1) {//免单
                        //判断开关是否打开
                        ServerResponse switchList = sySwitchService.findSwitchList(null, "免单不算6元奖励开关");
                        List<SySwitch> list = (List) switchList.getData();
                        if (CollectionUtils.isNotEmpty(list)) {
                            SySwitch sySwitch = list.get(0);
                            Integer state = sySwitch.getState();
                            log.info("免单不算6元奖励开关的状态{}：", state);
                            //开关打开：取消用户上级6元奖励
                            if (state == 1) {
                                return;
                            }
                        }
                    } else {
                        //如果不免单，商品单价是否超过指定金额，
                        log.info("神秘的单价{}", appOrderDetail.getPrice());
                        log.info("商品的单价{}", appOrderDetail.getItemPrice());
                        log.info("获取商品的实际支付金额{}", appOrderDetail.getAlipayTotalPrice());
                        if (appOrderDetail.getAlipayTotalPrice() == null || "".equals(appOrderDetail.getAlipayTotalPrice())) {
                            log.info("实际金额为空");
                            return;
                        }
                        BigDecimal itemPrice = new BigDecimal(appOrderDetail.getAlipayTotalPrice());
                        log.info("格式化单价{}", itemPrice);
                        BigDecimal orderpriceLimit = appUserRewardSetup.getInvitationRedMoneyOrderpriceLimit();
                        log.info("数据库设置的商品单价{}", orderpriceLimit);
                        if (itemPrice == null || orderpriceLimit == null) {
                            log.info("设置的商品限制阈值为空itemPrice{};orderpriceLimit{}", itemPrice, orderpriceLimit);
                            return;
                        }
                        //低于指定金额不给奖励，取消用户上级6元奖励
                        int i = itemPrice.compareTo(orderpriceLimit);
                        log.info("判断订单金额是否大于设定值{}", i);
                        if (i == -1) {
                            return;
                        }
                    }

                    long expireTime = DateFormatUtils.addDate(new Date(), appUserRewardSetup.getInvitationRedMoneyExpireTime()).getTime();
                    long invalidTime = DateFormatUtils.addDate(new Date(), appUserRewardSetup.getInvitationRedMoneyInvalidTime()).getTime();
                    log.info("任务红包的到期日期才能领取{},失效日期{}", expireTime, invalidTime);
                    //新增一条红包记录getPopupSearch
                    AppUserRedReward reward = new AppUserRedReward();
                    reward.setUserId(SJUser.getUserId());
                    reward.setHbTitle(appUserRewardSetup.getInvitationRedMoneyDesc());
                    reward.setHbMoney(appUserRewardSetup.getInvitationRedMoneyAmount());
                    reward.setHbType(2);//粉丝贡献
                    reward.setHbStatus(7);//7等待收货
                    reward.setCreateTime(new Date().getTime());
                    reward.setExpireTime(expireTime);//任务红包的到期日期才能领取
                    reward.setOrderId(appOrderDetail.getTradeId());//订单id
                    reward.setInvalidTime(invalidTime);//失效日期
                    reward.setFromUserId(appUser.getUserId());//被邀请人id
                    log.info("给上级增加一个5元红包数据");
                    add(reward);
                }

            }

        }

    }

    /**
     * 邀请赚钱文案
     *
     * @return
     */
    @Override
    public ServerResponse invitationDesc() {
        HashMap map = new HashMap();
        AppUserRewardSetup rewardSetup = iAppUserRewardSetupService.getAppUserRewardSetup(1);
        if (rewardSetup != null) {
            if (rewardSetup.getInvitationTwoDesc() != null) {
                map.put("invitationTwoDesc", rewardSetup.getInvitationTwoDesc());
            } else {
                map.put("invitationTwoDesc", "好友购物");
            }
            if (rewardSetup.getInvitationThreeDesc() != null) {
                map.put("invitationThreeDesc", rewardSetup.getInvitationThreeDesc());
            } else {
                map.put("invitationThreeDesc", "拿补贴");
            }

            return ServerResponse.createBySuccess("请求成功", map);
        } else {
            return ServerResponse.createBySuccess(201, "没有数据", null);
        }

    }

    /**
     * 邀请赚钱榜单1当月，2上个月
     *
     * @param monthType
     * @return
     */
    @Override
    public List<RedRewardInvitationListVo> findInvitationList(Integer monthType) {

        return appUserRedRewardMapper.findInvitationList(monthType);
    }

    /**
     * 邀请收益查粉丝列表-新
     *
     * @param userId
     * @param type
     * @return
     */
    @Override
    public List<Map> findMoneyListHbType(Long userId, Integer type) {
        List<Map> userOrderRedMoney = appUserRedRewardMapper.findMoneyListHbType(userId, type);
        for (Map userOrderRedMoneyaMap : userOrderRedMoney) {
            StringBuilder stringBuilder = new StringBuilder();
            Integer hbStatus = MapUtils.getInteger(userOrderRedMoneyaMap, "hbStatus");
            if (hbStatus == 6) {
                stringBuilder.append("用户未下单");
            } else if (hbStatus == 2 || hbStatus == 3) {
                stringBuilder.append("已收货，");
                stringBuilder.append("预计");
                Long expireTime = MapUtils.getLong(userOrderRedMoneyaMap, "expireTime");
                String s = DateFormatUtils.stampToDate2(expireTime, DateFormatUtils.STANDARD_FORMAT8);
                stringBuilder.append(s);
                stringBuilder.append("到账");
            } else if (hbStatus == 4) {
                stringBuilder.append("粉丝已退货奖励失效");
            } else if (hbStatus == 5) {
                stringBuilder.append("奖励已到账~");
            } else if (hbStatus == 7) {
                stringBuilder.append("已下单，待确认收货");
            }

            userOrderRedMoneyaMap.put("remark", stringBuilder.toString());
            userOrderRedMoneyaMap.remove("expireTime");
            userOrderRedMoneyaMap.remove("userId");

        }
        return userOrderRedMoney;
    }

    /**
     * 根据用户id 查询邀请收益金额
     *
     * @param userId
     * @return
     */
    @Override
    public Map invitationMakeMoneyByUserId(Long userId) {
        return appUserRedRewardMapper.invitationMakeMoneyByUserId(userId);
    }

    /**
     * 榜单造假数据
     *
     * @param type
     * @return
     */
    @Override
    public List<RedRewardInvitationListVo> findInvitationFakeList(Integer type) {
        return appUserRedRewardMapper.findInvitationFakeList(type);
    }

    @Override
    public List<AppUserRedRewardVo> queryUserRedRewardSm() {

        return appUserRedRewardMapper.queryUserRedRewardSm();
    }

    @Override
    public Integer selectStatusByIdAndType(Long userId, int type) {
        return appUserRedRewardMapper.selectStatusByIdAndType(userId, type);
    }

    @Override
    public Integer totalFissionNumber(Integer companyId, Integer flag) {
        return appUserRedRewardMapper.totalFissionNumber(companyId,flag);
    }

    @Override
    public Double totalRedEnvelopeForBeginners(Integer companyId,Integer type,Integer flag) {
        return appUserRedRewardMapper.totalRedEnvelopeForBeginners(companyId,type,flag);
    }

    @Override
    public String totalFirstPurchaseBonusPacket(Integer companyId,Integer flag) {
        return appUserRedRewardMapper.totalFirstPurchaseBonusPacket(companyId,flag);
    }

    @Override
    public Double totalSignAmount(Integer companyId, Integer flag) {
        return appUserRedRewardMapper.totalSignAmount(companyId,flag);
    }

    @Override
    public int totalRedEnvelopeForBeginnersCount(Integer companyId, Integer type, Integer flag) {
        return appUserRedRewardMapper.totalRedEnvelopeForBeginnersCount(companyId,type,flag);
    }

    @Override
    public String recommendedCommission(Integer companyId, Integer flag) {
        return appUserRedRewardMapper.recommendedCommission(companyId,flag);
    }

    /**
     * 2.30
     *
     * @param userId
     * @return
     */
    @Override
    public ServerResponse getMoneyListHbType(Long userId) {
        List<Map> userOrderRedMoney = appUserRedRewardMapper.getMoneyListHbType(userId);
        for (Map userOrderRedMoneyaMap : userOrderRedMoney) {
            StringBuilder stringBuilder = new StringBuilder();
            Integer hbStatus = MapUtils.getInteger(userOrderRedMoneyaMap, "hbStatus");
            if (hbStatus == 6) {
                stringBuilder.append("粉丝还未下单~");
            } else if (hbStatus == 3) {
                stringBuilder.append("已到账，可以提取奖励啦~");
            } else if (hbStatus == 2) {
                stringBuilder.append("已收货，");
                String hbMoney = MapUtils.getString(userOrderRedMoneyaMap, "hbMoney");
                stringBuilder.append(hbMoney);
                stringBuilder.append("元奖励预计");
                Long expireTime = MapUtils.getLong(userOrderRedMoneyaMap, "expireTime");
                String s = DateFormatUtils.stampToDate2(expireTime, DateFormatUtils.STANDARD_FORMAT8);
                stringBuilder.append(s);
                stringBuilder.append("到账");
            } else if (hbStatus == 4) stringBuilder.append("粉丝退货已失效");
            else if (hbStatus == 5) stringBuilder.append("提取过奖励了");
            else if (hbStatus == 7) stringBuilder.append("已下单，待确认收货");

            userOrderRedMoneyaMap.put("remark", stringBuilder.toString());

        }
        return ServerResponse.createBySuccess("查询成功", userOrderRedMoney);
    }

    @Override
    public int updateRedMoneyStatusSx(Long time) {
        return appUserRedRewardMapper.updateRedMoneyStatusSx(time);
    }

    @Override
    public int updateNewRedMoneyStatusSx(long time) {
        return appUserRedRewardMapper.updateNewRedMoneyStatusSx(time);
    }

}
